package com.zzy.transaction.task;

import com.zzy.transaction.context.TransactionMeta;
import com.zzy.transaction.manager.TransactionCoordinator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class TransactionTask implements Runnable {

    private TransactionMeta transactionMeta;
    private Runnable task;

    public TransactionTask(Runnable task) {
        this.transactionMeta = TransactionCoordinator.get();
        this.task = task;
    }

    public static TransactionTask of(Runnable task) {
        TransactionTask transactionTask = new TransactionTask(task);
        return transactionTask;
    }

    @Override
    public void run() {
        try {
            TransactionCoordinator.bind(this.transactionMeta);
            this.task.run();
        } catch (Throwable e) {
            // log.error("事务:{},执行失败", this.transactionMeta.getExecuteId(), e);
        } finally {
            TransactionCoordinator.unbind();
        }
    }
}
